package priv.utrix.micro.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import priv.utrix.micro.entity.SysRole;
import priv.utrix.micro.json.ApiController;
import priv.utrix.micro.json.R;
import priv.utrix.micro.service.SysRoleService;
import priv.utrix.micro.utils.RedisUtil;

import javax.validation.Valid;

/**
 * @author utrix
 * @date 2021/1/29
 */
@RestController
@RequestMapping("/sysRole")
@RequiredArgsConstructor
@CacheConfig(cacheNames = "sysRole")
public class SysRoleController extends ApiController {

    private final RedisUtil redisUtil;
    private final SysRoleService roleService;

    private static final String CACHE_KEY_PREFIX = "sysRole::";

    @GetMapping("/{id}")
    @Cacheable(key = "#id", unless = "#result.code == 303")
    public R<SysRole> getById(@PathVariable("id") Integer id) {
        SysRole byId = roleService.getById(id);
        return byId == null ? failed() : success(byId);
    }

    @PostMapping
    // @Cacheable(key = "#id")
    public R<String> add(@Valid SysRole role) {
        boolean save = roleService.save(role);
        if (save) {
            String key = CACHE_KEY_PREFIX + role.getId();
            if (redisUtil.isKey(key)) {
                redisUtil.remove(key);
            }
            redisUtil.set(key,role);
            return success();
        }

        return failed();
    }

    @PutMapping
    // @CachePut(key = "#id")
    public R<String> update(@Valid SysRole role) {
        boolean update = roleService.updateById(role);
        // 手动缓存
        if (update) {
            String key = CACHE_KEY_PREFIX + role.getId();
            if (redisUtil.isKey(key)) {
                redisUtil.remove(key);
            }
            redisUtil.set(key,role);
            return success();
        }

        return failed();
    }

    @DeleteMapping
    @CacheEvict(key = "#id")
    public R<String> delete(@RequestParam Integer id) {
        boolean delete = roleService.removeById(id);
        return delete ? success() : failed();
    }

}
